package com.youan.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youan.pangu.base.exception.BusinessException;
import com.youan.pangu.base.bean.ElementTree;
import com.youan.serve.dao.domain.Org;
import com.youan.serve.dao.domain.User;
import com.youan.serve.dao.idao.OrgMapper;
import com.youan.serve.service.IOrgService;
import com.youan.serve.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author auto_code
 * @since 2020-03-04
 */
@Service
public class OrgServiceImpl extends ServiceImpl<OrgMapper, Org> implements IOrgService {

    @Autowired
    private IUserService userService;

    @Override
    public List<ElementTree> getOrgs() throws Exception {
        List<ElementTree> elementTreeList = new ArrayList<ElementTree>();
        List<Org> orgList = this.list();
        elementTreeList = setTree(orgList, "");
        return elementTreeList;
    }

    public List<ElementTree> setTree(List<Org> organizationList, String parentId) throws Exception {
        List<ElementTree> elementTreeList = new ArrayList<ElementTree>();
        for(Org org : organizationList){
            if((org.getParentId()==null && parentId.equals("")) || (org.getParentId()!=null && org.getParentId().equals(parentId)) ){
                org.setId();
                org.setLabel();
                org.setChildren(setTree(organizationList, org.getOrgId()));
                elementTreeList.add(org);
            }
        }
        return elementTreeList;
    }

    @Override
    public void deleteOrg(String orgId) throws Exception {
        if (orgId == null || orgId.equals("")) {
            throw new BusinessException("删除机构时传入的机构id不存在！");
        }

        List<Org> organizationList = this.list(new LambdaQueryWrapper<Org>().eq(Org::getParentId, orgId));
        if(organizationList.size()>0){
            throw new BusinessException("该机构存在子机构，不允许删除！");
        }

        List<User> userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getOrgId, orgId));
        if(userList.size()>0){
            throw new BusinessException("该机构下存在用户，不允许删除！");
        }
        this.removeById(orgId);
    }
}
